package com.ews.onlineexchange.controller;

import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.CheckboxTreeNode;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.TreeNode;

import com.ews.onlineexchange.dao.SectorDao;
import com.ews.onlineexchange.model.Image;
import com.ews.onlineexchange.model.QualificationCert;
import com.ews.onlineexchange.model.QualificationTemplate;
import com.ews.onlineexchange.model.Sector;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.service.EntityHome;
import com.ews.onlineexchange.service.RejectRecordHome;
import com.ews.onlineexchange.service.UserService;
import com.ews.onlineexchange.util.AttachmentUtils;

@Named
@ConversationScoped
public class UnauditCertHome extends EntityHome<QualificationCert, String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	RejectRecordHome rejectRecordHome;
	
	private QualificationTemplate currentQualificationTemplate;
	private Integer currentQualificationTemplateIndex = 0; 
	private  Map<Integer, TreeNode> rootNodeMap = new HashMap<>();
	private  Map<Integer, TreeNode[]> selectedNodeMap = new HashMap<>();


		
	@Inject
	UserService userService;
	@Override
	public String saveAndFlush() {
		List<QualificationTemplate> templates = getInstance().getQualificationTemplates();
		for (QualificationTemplate qualificationTemplate : templates) {
			if(qualificationTemplate.getSectors().size() == 0) {
				FacesContext.getCurrentInstance().addMessage("certPhotos",
						new FacesMessage(FacesMessage.SEVERITY_ERROR, "资质证书需要选择行业范围！", ""));
				return null;
			}
		}
		ServiceSupplier user = (ServiceSupplier) userService.getLoginedUser();
		getInstance().setServiceSupplier(user);
		getInstance().setAuditResult(null);
		getInstance().setValid(false);
		getInstance().setCurrRejectRecord(null);
		return super.saveAndFlush();
	}
	
	
	
	@Override
	public String delete() {
		// TODO Auto-generated method stub
		ServiceSupplier supplier = getInstance().getServiceSupplier();
		supplier.getCerts().remove(getInstance());
		getInstance().setServiceSupplier(null);
		
		return super.delete();
	}



	@Override
	public QualificationCert createInstance() {
		QualificationCert instance = super.createInstance();
		instance.addEmptyQualificationTemplate();
		return instance;
	}

	public QualificationTemplate getCurrentQualificationTemplate() {
		return currentQualificationTemplate;
	}

	public void setCurrentQualificationTemplate(QualificationTemplate currentQualificationTemplate) {
		this.currentQualificationTemplate = currentQualificationTemplate;
	}

	public Integer getCurrentQualificationTemplateIndex() {
		return currentQualificationTemplateIndex;
	}

	public void setCurrentQualificationTemplateIndex(Integer currentQualificationTemplateIndex) {
		this.currentQualificationTemplateIndex = currentQualificationTemplateIndex;
	}
	
	
	
	public Map<Integer, TreeNode> getRootNodeMap() {
		return rootNodeMap;
	}

	public void setRootNodeMap(Map<Integer, TreeNode> rootNodeMap) {
		this.rootNodeMap = rootNodeMap;
	}

	public Map<Integer, TreeNode[]> getSelectedNodeMap() {
		return selectedNodeMap;
	}

	public void setSelectedNodeMap(Map<Integer, TreeNode[]> selectedNodeMap) {
		this.selectedNodeMap = selectedNodeMap;
	}
	
	private Object getSectorMap(String id, String name, String parentId) {
		Map<String, String> sectorFieldMap = new HashMap<>();
		sectorFieldMap.put("id", id);
		sectorFieldMap.put("name", name);
		sectorFieldMap.put("parentId", parentId);
		return sectorFieldMap;
	}
	
	@Inject
	SectorDao sectorDao;
	
	public List<Object[]> getSectorTree(String rootId) {
		List<Object[]> sectorTree = sectorDao.querySectorInTree(rootId);		
		return sectorTree;
	}
	
	private TreeNode getRootSectorNode() {
		
		TreeNode rootNode = new CheckboxTreeNode(getSectorMap(null, "行业列表", null), null);
		Map<String, TreeNode> tnMap = new HashMap<>();
	
		for (Sector sector : getInstance().getQualificationClass().getRootSectors()) {
			List<Object[]> sectorList = sectorDao.querySectorInTree(sector.getId());
			for (Object[] objects : sectorList) {
				String id = (String) objects[0];
				String name = (String) objects[1];
				String parentId = (String) objects[2];
				
				TreeNode tn = null;
				TreeNode parentNode = tnMap.get(parentId);	
				if (parentNode != null) {
					tn = new CheckboxTreeNode(getSectorMap(id, name, parentId), parentNode);
				} else {
					tn = new CheckboxTreeNode(getSectorMap(id, name, parentId), rootNode);
					rootNode.getChildren().add(tn);
				}
				tnMap.put(id, tn);
			}
		}
		
		return rootNode;
	}
	
	public void initRootNode() {	
		TreeNode rootNode = null;
		if (rootNodeMap.get(getCurrentQualificationTemplateIndex()) == null) {
			rootNode = getRootSectorNode();
			rootNodeMap.put(currentQualificationTemplateIndex, rootNode);
		}
	}
	
	public void clearTemplateSectors() {
		rootNodeMap.clear();
		selectedNodeMap.clear();
		for (QualificationTemplate template : getInstance().getQualificationTemplates()) {
			template.getSectors().clear();
		}
	}
	
	
	
	public void addCurrentCertSectorId(String id) {
		
		Sector sector = sectorDao.find(id);
		getCurrentQualificationTemplate().getSectors().add(sector);
	}
	
	public void chooseSectors() {
		getCurrentQualificationTemplate().getSectors().clear();
		getCurrentQualificationTemplate().setQualificationClass(getInstance().getQualificationClass());
		TreeNode[] currentTree = getSelectedNodeMap().get(getCurrentQualificationTemplateIndex());
		for (TreeNode treeNode : currentTree) {
			if (treeNode.getChildCount() > 0)
				continue;
			String id = ((HashMap<String, String>)treeNode.getData()).get("id");
			addCurrentCertSectorId(id);
		}
	}
	@Inject
	AttachmentUtils attachmentUtils;
	public void uploadCertPhotos(FileUploadEvent event) {
		if (event.getFile() == null)
			return ;
		Image attr = attachmentUtils.getImageFromUpload(event.getFile());
		attr.generateThumbnail();
		this.getInstance().getCertPhotos().add(attr);
		FacesMessage message = new FacesMessage(event.getFile().getFileName() + " 上传成功。");
        FacesContext.getCurrentInstance().addMessage(null, message);
	}
	
	public void removeCertPhoto(Image photo) {
		this.getInstance().getCertPhotos().remove(photo);
	}
	
	public StreamedContent getPhotoStreamedContent(Image image) {
		if (image == null)
			return null;
		return new DefaultStreamedContent(new ByteArrayInputStream(image.getThumbnailData()));
	}
}
